package com.sl.au.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.ArchiveReportInfo;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.VisitorReward;
import com.sl.au.entity.ViewForVisitorReward;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.Option;
import com.sl.au.service.ArchiveReportInfoService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.OptionService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.VisitorRewardProcessingService;
import com.sl.au.service.VisitorRewardService;
import com.sl.utils.MsgHelper;

@RestController
@RequestMapping("/ui/archiveReport")
public class ArchiveReportInfoController extends BaseController {
	@Autowired
	private EventReportService eventReportService;
	@Autowired
	private OptionService optionService;
	@Autowired
	private ArchiveReportInfoService archiveReportInfoService;

	@Autowired
	private OperateLogService operateLogService;
	@Autowired
	private EventRegisterService eventRegisterService;
	@Autowired
	private VisitorRewardProcessingService visitorRewardProcessingService;
	@Autowired
	private VisitorRewardService visitorRewardService;

	@RequestMapping(value = "/showDetailRegisters", method = RequestMethod.POST)
	public Map<String, Object> showDetailRegisters(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String reportId = request.getParameter("key");
		List<EventRegister> infos = null;

		infos = archiveReportInfoService.showDetailRegisters(reportId, start, length);

		int count = archiveReportInfoService.showDetailRegistersCount(reportId);

		map.put("data", infos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/initArchivedPage", method = RequestMethod.POST)
	public Map<String, Object> initArchivedPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
//		List<ArchiveReportInfo> infos = null;
//		if (StringUtils.hasText(key)) {
//			infos = archiveReportInfoService.initArchivedPageByKey(key, start, length);
//		} else {
//			infos = archiveReportInfoService.initArchivedPageNoKey(start, length);
//		}
//		int count = archiveReportInfoService.getArchivedCount(key);

		List<Map<String, Object>> infos = null;
		String roleId = this.getMyAccount().getRole().getId();
		infos = archiveReportInfoService.initArchivedPageByKeyAndRole(start, length, roleId, key, "createTime", "DESC");
		int count = archiveReportInfoService.getArchivedCountByRole(roleId, key);

		map.put("data", infos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping("/archiveFinishedReport/{reportId}")
	public MsgHelper archiveFinishedReport(@PathVariable("reportId") String reportId,
			ArchiveReportInfo archiveReportInfo) {
		Option option = optionService.getRepository().findByGroupAndTitle("事件上报状态", "已归档").get(0);
		EventReport report = eventReportService.getRepository().findOne(reportId);
		report.setReportEventVariable(option);

		archiveReportInfo.setArcheveDate(new Date());
		archiveReportInfo.setArchiver(getMyAccount().getUser());
		archiveReportInfo.setDealer(getMyAccount().getUser());

		archiveReportInfoService.saveMany(report, archiveReportInfo, new EventTask());

		// 短信通知
		sendMsgToReportUser(report);
		// ------------

		return MsgHelper.success();
	}

	@RequestMapping(value = "/archiveFinishedReportDirectly/{reportId}", method = RequestMethod.POST)
	public MsgHelper archiveFinishedReportDirectly(@PathVariable("reportId") String reportId) {
		Option option = optionService.getRepository().findByGroupAndTitle("事件上报状态", "已归档").get(0);
		EventReport report = eventReportService.getRepository().findOne(reportId);
		report.setReportEventVariable(option);
		ArchiveReportInfo archiveReportInfo = new ArchiveReportInfo();
		archiveReportInfo.setMemo("通过直接归档按钮进行归档");
		archiveReportInfo.setContent("通过直接归档按钮进行归档");
		archiveReportInfo.setArcheveDate(new Date());
		archiveReportInfo.setArchiver(getMyAccount().getUser());
		archiveReportInfo.setDealer(getMyAccount().getUser());

		archiveReportInfoService.saveMany(report, archiveReportInfo, new EventTask());

		// 短信通知
		sendMsgToReportUser(report);
		// ------------
		return MsgHelper.success();
	}

	/*
	 * 发送推送消息给上报用户
	 */
	private void sendMsgToReportUser(EventReport info) {
		try {
			if (info != null) {
				List<EventRegister> registers = this.eventRegisterService.findByReportId(info.getId());
				String identifys = "";
				if (registers != null) {
					for (int i = 0; i < registers.size(); i++) {
						identifys += registers.get(i).getRegisterEventIdentify() + ",";
					}
				}
				if (identifys != "") {
					identifys = identifys.substring(0, identifys.length() - 1);
				}
				double singleScal = 0;
				VisitorReward visitorReward;
				visitorReward = this.visitorRewardService.getRepository().findByEventRegister(info.getId());
				if (visitorReward != null) {
					singleScal = visitorReward.getRewardValue();
				}

				double scale = 0;
				ViewForVisitorReward viewForVisitorReward;
				String phoneList = "";
				if (info.getReportUser() != null) {
					viewForVisitorReward =this.visitorRewardProcessingService.getViewForVisitorRewardRepository()
							.findOne(info.getReportUser().getId());
					if(viewForVisitorReward!=null){
						scale = viewForVisitorReward.getTotalRewardValue();
					}
					phoneList = info.getReportUser().getContactType();
				}
				if (phoneList != null && phoneList != "") {
					// 短信通知
					String content = "【重庆市智博会】您上报的案件[" + identifys + "]，已处理，现已结案归档，该案件积[" + singleScal
							+ "]分，您现已累计积分[" + scale + "]分。积分可以参与兑奖哦，感谢您对城市管理的支持！";

					Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "案件归档通知");
					if (op != null) {
						content = op.getTitle();
					}
					content = content.replace("{0}", identifys);
					content = content.replace("{1}", Double.toString(singleScal));
					content = content.replace("{2}", Double.toString(scale));
					Map<String, Object> mapTemp = this.sendMessage(phoneList, content);
					if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
						// 是否记录日志
						operateLogService.log(this.getMyAccount().getUser(), "案件归档通知", content);
					} else {
						operateLogService.log(this.getMyAccount().getUser(), "案件归档通知", "发送案件归档通知失败!");
					}
					// ------------
				}
			}
		} catch (Exception ex) {

		}

	}

	@RequestMapping(value = "/initRegisters/{reportId}", method = RequestMethod.POST)
	public Map<String, Object> initRegisters(@PathVariable("reportId") String reportId, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));

		List<EventRegister> infos = eventRegisterService.getRegistersPageByReportId(reportId, start, length);

		int count = eventRegisterService.getRegistersCountByReportId(reportId);

		map.put("data", infos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping("/archiveFinishedReportUI/{reportId}")
	public ModelAndView archiveFinishedReportUI(@PathVariable("reportId") String reportId) {
		ModelAndView modelAndView = createLayoutView("archiveReport/archiveFinishedReportUI");
		modelAndView.addObject("reportId", reportId);
		return modelAndView;
	}

	@RequestMapping(value = "/initFinishedReports", method = RequestMethod.POST)
	public Map<String, Object> initFinishedReports(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		// 已完结的事件源
		Option option = optionService.getRepository().findByGroupAndTitle("事件上报状态", "已完结").get(0);
//		List<EventReport> infos = null;
//
//		if (StringUtils.hasText(key)) {
//			infos = eventReportService.getFinishedReportPageByKey(start, length, key, option.getId());
//		} else {
//			infos = eventReportService.getFinishedReportPageNoKey(start, length, option.getId());
//		}
//
//		// List<GridAreaInfo> bindDivisionGridsNoPage=new ArrayList<>();
//		int count = 0;
//		count = eventReportService.getFinishedReportCount(key, option.getId());// gridinfoservice.getCount(key);
		String roleId = this.getMyAccount().getRole().getId();
		List<Map<String,Object>> infos = null;
		infos = eventReportService.getFinishedReportPageByKeyAndRole(start, length, roleId, key, option.getId(), "createTime", "DESC");
		int count = 0;
		count = eventReportService.getFinishedReportCountByRole(roleId, key, option.getId());
		map.put("data", infos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {

		modelAndView = createLayoutView("archiveReport/index");

		return modelAndView;
	}
}
